package com.gopay.cron.event.handler;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.gopay.common.datasource.DBType;
import com.gopay.common.datasource.DbContextHolder;
import com.gopay.common.domain.report.Event;
import com.gopay.common.event.EventState;
import com.gopay.common.event.handler.EventHandler;
import com.gopay.common.exception.GopayException;
import com.gopay.common.report.dao.MqEventInfoDAO;
import com.gopay.cron.event.manager.EventHandlerManager;
import com.gopay.cron.service.trans.ReportConsoleTransQueryService;
import com.gopay.cron.service.trans.TransQueryService;
import com.gopay.cron.web.vo.TransQueryResultVO;

@Service(value="updateEventDefaultHandler")
public class UpdateEventDefaultHandler implements EventHandler {
    private Logger log = LoggerFactory.getLogger(UpdateEventDefaultHandler.class);
    @Resource
    private TransQueryService transQueryService;
    private Calendar c = Calendar.getInstance();  
    @Resource 
    private ReportConsoleTransQueryService reportConsoleTransQueryService;
    @Resource(name="mqEventInfoDAO")
    private MqEventInfoDAO mqEventInfoDAO;
    @Resource(name = "updateEventHandlerManager")
    private EventHandlerManager updateEventHandlerManager;
    
    @Override
    public void handler(Event e) throws GopayException {
        
        
        Map<String, Object> map =StringUtils.isNotBlank(e.getSnapshot())? (Map<String, Object>) JSONObject.parse(e.getSnapshot()):new HashMap<String, Object>();
        if(StringUtils.isNotBlank(e.getGopayOrderId())){
            map.put("gopayOrderId", e.getGopayOrderId());
        }
        List<TransQueryResultVO> transQueryResultList = null;
        try {
            
            transQueryResultList = reportConsoleTransQueryService.getTransQueryResultList(map);
           
        } catch (GopayException e1) {
            log.error("UpdateEventDefaultHandler 执行出错", e1);
            throw e1;
        }
       
        
        if(null != transQueryResultList && transQueryResultList.size() > 0){
            updateEventHandlerManager.saveOrUpdateOrderAndEvent(transQueryResultList, e);
        }else{
            DbContextHolder.setDbType(DBType.DS_REPORT.value);
            Event result = mqEventInfoDAO.find(Event.class, e.getId());
            result.setStat(EventState.FAIL.value);
            mqEventInfoDAO.update(result);
        }
        
       
    }


}
